package com.six.backend.shiro;
import com.six.backend.pojo.User;
import com.six.backend.service.RolePermissionService;
import com.six.backend.service.RoleService;
import com.six.backend.service.UserService;
import com.six.backend.token.JwtToken;
import com.six.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @Author: skyler
 * @Date: 2021/11/6 11:07
 */
public class UserRealm  extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权");
        String account = (String) principals.iterator().next();
        Set<String> roles = roleService.selectRoleNameByAccount(account);
        Set<String> permissions = rolePermissionService.selectPermissionByAccount(account);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }


    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");
        JwtToken jwtToken = (JwtToken) token;
        String jwt = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(jwt);
        String account = claims.getId();
        User realuser = userService.selectUserBYId(account);
        if (realuser == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(account,realuser.getPassword(),this.getName());
    }
}
